<template>
  <div class="app-tab-content">
    <ul ref="appTab">
      <li v-for="(item,index) in labs" :style="itemsStyle[index]"
          @click="clickItem(item.id)" :key="index" :id="item.id"
          :class="item.id === selectedItem ? 'selected' : ''">
        {{item.text}}
      </li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: 'AppTab',
    data () {
      return {
        id: 100,
        selectedItem: this.selectedId,
        itemsStyle: []
      }
    },
    mounted () {
      this.renderResize()
      window.addEventListener('resize', this.renderResize, false)
    },
    destroyed () {
      window.removeEventListener('resize', this.renderResize)
    },
    methods: {
      clickItem (id) {
        this.selectedItem = id
      },
      renderResize () {

        let width = document.documentElement.clientWidth
        const height = document.documentElement.clientHeight

        if (width < height) {
          width = height
        }
        if (width < itemsWidth) {
          return
        }

        const itemArray = this.$refs.appTab.children
        const itemsWidth = this.$refs.appTab.clientWidth
        let surplusWidth = width - itemsWidth
        for (let index = 0; index < itemArray.length; index++) {
          let itemWidth = itemArray[index].clientWidth
          itemWidth += (itemWidth / itemsWidth) * surplusWidth
          // 这里根据样式(padding)需要修改(.4rem)宽度计算的值
          this.itemsStyle.push('width: calc(' + itemWidth + 'px - .4rem);')
        }
      }
    },
    watch: {
      labs () {
        this.renderResize()
      }
    },
    props: {
      selectedId: {
        type: Number,
        default: 1
      },
      labs: {
        type: Array,
        default: () => [
          {
            id: 1,
            text: '热点'
          },
          {
            id: 2,
            text: '实时'
          },
          {
            id: 3,
            text: '爆炸'
          },
          {
            id: 4,
            text: '本地'
          },
          {
            id: 5,
            text: '全球'
          },
          {
            id: 6,
            text: '外星'
          },
          {
            id: 7,
            text: '银河'
          },
          {
            id: 8,
            text: '宇宙'
          },
          {
            id: 9,
            text: '虚无'
          }
        ]
      }
    }
  }
</script>

<style lang="less" scoped>
  .app-tab-content {
    width: 100%;
    overflow-x: auto;
    white-space: nowrap;
    background-color: white;

    ul {
      list-style-type: none;
      display: inline-block !important;

      li {
        width: auto;
        text-align: center;
        padding: .3rem .2rem;
        display: inline-block !important;

        &.selected {
          border-bottom: 3px palevioletred solid;
        }
      }
    }

    &::-webkit-scrollbar {
      display: none;
    }
  }
</style>
